package gang.org.springframework.framework.util;

/**
 * @author gang.chen
 * @description
 * @Date 2021/6/21 12:45
 */
public abstract class GangClassUtils {

    private static final char PACKAGE_SEPARATOR = '.';

    private static final char PATH_SEPARATOR = '/';

    public static final String CLASS_FILE_SUFFIX = ".class";

    public static String getShortName(String className)
    {
        int lastDotIndex = className.lastIndexOf(PACKAGE_SEPARATOR);
        int nameEndIndex = className.length();
        String shortName = className.substring(lastDotIndex+1, nameEndIndex);
        return shortName;
    }

    //TODO
    public static Class<?> resolvePrimitiveIfNecessary(Class<?> clazz){
        return clazz.isPrimitive() && clazz != void.class?null:clazz;
    }

    //TODO
    public static Class<?> forName(String name, ClassLoader classLoader){
        ClassLoader cloToUse = classLoader;
        try {
            return Class.forName(name,false,cloToUse);
        }
        catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static String convertClassNameToResourcePath(String className){
        return className.replace(PACKAGE_SEPARATOR,PATH_SEPARATOR);
    }

    public static String convertResourcePathToClassName(String resourcePath){
        return resourcePath.replace(PATH_SEPARATOR,PACKAGE_SEPARATOR);
    }

    //TODO
    public static ClassLoader getDefaultClassLoader(){
        ClassLoader classLoader = null;
        classLoader = Thread.currentThread().getContextClassLoader();
        return classLoader;
    }

    /**
     * TODO
     * @param lhsType 接口
     * @param rhsType 实现类
     * */
    public static boolean isAssignable(Class<?> lhsType, Class<?> rhsType){
        if (lhsType.isAssignableFrom(rhsType)) {
            return true;
        }
        return false;
    }

    /**
     * 业务意义
     * clazz1 方法返回对象 {@link gang.org.springframework.framework.web.servlet.config.annotation.GangWebMvcConfigurationSupport}
     * */
    public static Class<?> determineCommonAncestor(Class<?> clazz1, Class<?> clazz2){
        if (clazz1 == null) {
            return clazz2;
        }
        if (clazz2 == null) {
            return clazz1;
        }
        return null;
    }

    public static boolean isPresent(String className, ClassLoader classLoader){

        try {
            forName(className,classLoader);
            return true;
        }catch (Exception e){
            return false;
        }
    }

    public static Class<?> getUserClass(Class<?> clazz){
        if (clazz.getName().contains("$$")) {
            //TODO
        }
        return clazz;
    }
}
